package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.domain.FamilyMemberElder;
import com.zzyl.nursing.dto.ElderToMemberDto;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.DeviceDataListByDayAndWeekVo;
import com.zzyl.nursing.vo.DeviceShadowDataVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.MemberFamilyDeviceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 * 
 * @author laoYe
 * @date 2025-10-27
 */
@Service
@Slf4j
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired// 要使用若依框架
    private TokenService tokenService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    private static List<String> DEFAULT_NICKNAME_PREFIX = List.of(
        "生活更美好",
        "大桔大利",
        "日富一日",
        "好柿开花",
        "柿柿如意",
        "一椰暴富",
        "大柚所为",
        "杨梅吐气",
        "天生荔枝"
    );

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        // 创建一个vo
        LoginVo vo = new LoginVo();
        //1. 获取openId
        String openId = wechatService.getOpenId(dto.getCode());
        //2. 获取用户的手机号码
        String phone = wechatService.getPhoneNumber(dto.getPhoneCode());
        //3. 通过openId查询用户信息
        FamilyMember memberInDB = lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        // 创建一个保存的实体类
        FamilyMember newFamilyMember = new FamilyMember();
        // 设置要保存的手机号码
        newFamilyMember.setPhone(phone);
        //4. 判断用户是否存在
        if(memberInDB != null) {
            vo.setNickName(memberInDB.getName());
            // 更新条件为主键id
            newFamilyMember.setId(memberInDB.getId());
            //5. 存在
            // 手机号码是否有变更，有变更则要更新
            if(!memberInDB.getPhone().equals(phone)) {
                //update 表名 set 字段名 = 值 where id = ?, 明确更新的字段
                updateById(newFamilyMember);
            }
        }else {
            //6. 不存在,新增
            newFamilyMember.setOpenId(openId);
            // 昵称
            // 随机组装昵称，词组+手机号后四位
            String nickName = generateNickname(phone);
            newFamilyMember.setName(nickName);
            save(newFamilyMember);
            vo.setNickName(nickName);
        }
        //7. 把用户id与nickname封装到token返回
        Map<String,Object> claims = new HashMap<String,Object>();
        claims.put("userId", newFamilyMember.getId());
        claims.put("nickName", vo.getNickName());
        String token = tokenService.createToken(claims);
        vo.setToken(token);
        return vo;
    }

    /**
     * 生成随机昵称
     * @param phone
     * @return
     */
    private String generateNickname(String phone) {
        Random r = new Random();
        int prefixIndex = r.nextInt(DEFAULT_NICKNAME_PREFIX.size());
        String prefix = DEFAULT_NICKNAME_PREFIX.get(prefixIndex);
        // 手机号后四位
        String suffix = phone.substring(phone.length() - 4);
        return prefix + suffix;
    }

    /**
     * 添加老人和家属关系
     * @param dto
     */
    @Override
    public void add(ElderToMemberDto dto) {
        //通过身份证和名字查询老人是否存在
        Elder elder = elderMapper.selectOne(new QueryWrapper<Elder>().eq("id_card_no", dto.getIdCard()).eq("name", dto.getName()));
        //Elder elder = elderMapper.selectOne(new QueryWrapper<Elder>().eq("id_card_no", dto.getIdCard()));
        if (ObjectUtil.isEmpty(elder)){
            throw new ServiceException("该老人不存在");
        }
        //判断该老人是否已经和当前用户有关系
        FamilyMemberElder familyMemberElderInDB = familyMemberElderMapper.selectOne(new QueryWrapper<FamilyMemberElder>().eq("elder_id", elder.getId()).eq("family_member_id", UserThreadLocal.getUserId()));
        if (ObjectUtil.isNotEmpty(familyMemberElderInDB)){
            throw new ServiceException("该老人已经和当前用户有关系");
        }
        //创建客户老人与家属关联的对象
        FamilyMemberElder familyMemberElder = new FamilyMemberElder();
        familyMemberElder.setElderId(elder.getId());
        //获取当前登录的用户的id
        Long userId = UserThreadLocal.getUserId();
        familyMemberElder.setFamilyMemberId(userId);
        //添加更新人id
        familyMemberElder.setUpdateBy(userId.toString());
        //添加创建人id
        familyMemberElder.setCreateBy(userId.toString());
        //添加备注
        familyMemberElder.setRemark(dto.getRemark());
        //添加进数据库
        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 按天统计查询指标数据
     * @param
     * @return
     */
    @Override
    public List<DeviceDataListByDayAndWeekVo> queryDeviceDataListByDay(String iotId, String functionId, Long startTime, Long endTime) {
        // 指定时区
        ZoneId zoneId = ZoneId.of("Asia/Shanghai");
        // 转换成LocalDateTime
        LocalDateTime startLocalDateTime = Instant.ofEpochMilli(startTime).atZone(zoneId).toLocalDateTime();
        LocalDateTime endLocalDateTime = Instant.ofEpochMilli(endTime).atZone(zoneId).toLocalDateTime();
        log.info("开始时间：{}", startLocalDateTime);
        log.info("结束时间：{}", endLocalDateTime);
        // 从数据库查询
        List<DeviceDataListByDayAndWeekVo> dbData = deviceDataMapper.selectHourlyData(iotId, functionId, startLocalDateTime, endLocalDateTime);
        log.info("dbData:{}", dbData);
        // 2. 构建 24 小时完整时间列表
        List<String> allHours = new ArrayList<>();
        for (int hour = 0; hour < 24; hour++) {
            allHours.add(String.format("%02d:00", hour));
        }

        // 3. 将数据库结果转为 Map 便于查找
        Map<String, Double> dbDataMap = dbData.stream()
                .collect(Collectors.toMap(DeviceDataListByDayAndWeekVo::getDateTime, DeviceDataListByDayAndWeekVo::getDataValue));

        // 4. 补全缺失小时（设为 0.0）
        return allHours.stream()
                .map(hour -> {
                    DeviceDataListByDayAndWeekVo dto = new DeviceDataListByDayAndWeekVo();
                    dto.setDateTime(hour);
                    dto.setDataValue(dbDataMap.getOrDefault(hour, 0.0)); // 缺失值设为 0.0
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 按周统计查询指标数据
     * @param
     * @return
     */
    @Override
    public List<DeviceDataListByDayAndWeekVo> queryDeviceDataListByWeek(String iotId, String functionId, Long startTime, Long endTime) {
        // 1. 生成时间范围内的所有日期（MM.dd格式）
        LocalDate start = Instant.ofEpochMilli(startTime).atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate end = Instant.ofEpochMilli(endTime).atZone(ZoneId.systemDefault()).toLocalDate();

        List<String> allDates = new ArrayList<>();
        LocalDate current = start;
        while (!current.isAfter(end)) {
            allDates.add(current.format(java.time.format.DateTimeFormatter.ofPattern("MM.dd")));
            current = current.plusDays(1);
        }

        // 2. 查询数据库中实际存在的数据
        List<DeviceDataListByDayAndWeekVo> dbData = deviceDataMapper.selectDailyData(iotId, functionId, startTime, endTime);

        // 3. 构建日期-值映射
        Map<String, Double> dbDataMap = dbData.stream()
                .collect(Collectors.toMap(DeviceDataListByDayAndWeekVo::getDateTime, DeviceDataListByDayAndWeekVo::getDataValue));

        // 4. 补全缺失日期（设为0.0）
        return allDates.stream()
                .map(date -> {
                    DeviceDataListByDayAndWeekVo dto = new DeviceDataListByDayAndWeekVo();
                    dto.setDateTime(date);
                    dto.setDataValue(dbDataMap.getOrDefault(date, 0.0));
                    return dto;
                })
                .collect(Collectors.toList());
    }

    /**
     * 查询家人列表
     * @return
     */
    @Override
    public List<MemberFamilyDeviceVo> queryMemberElderList() {
        //获取当前登录用户的id
        Long userId = UserThreadLocal.getUserId();
        //根据用户id查询
        List<MemberFamilyDeviceVo> familyMemberElderList = familyMemberElderMapper.selectFamilyWithElder(userId);
        if (CollUtil.isEmpty(familyMemberElderList)){
            return new ArrayList<>();
        }
        return familyMemberElderList;
    }

    /**
     * 查看已绑定家人列表（分页查询）
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<MemberFamilyDeviceVo> queryMemberElderPage(Integer pageNum, Integer pageSize) {
        //获取当前登录用户的id
        Long userId = UserThreadLocal.getUserId();
        //设置分页参数
        // 1. 创建 MyBatis-Plus 分页对象
        Page<MemberFamilyDeviceVo> page = new Page<>(pageNum, pageSize);

        // 2. 调用 Mapper 分页查询（自动 COUNT + LIMIT）
        IPage<MemberFamilyDeviceVo> resultPage =
                familyMemberElderMapper.selectFamilyWithElderByPage(page, userId);

        // 3. 封装到自定义分页实体
        return resultPage.getRecords();

    }

    /**
     * 查询健康数据
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceShadowDataVo> queryServiceProperties(String iotId) {
        //获取redis中这个设备最新的数据
        String jsonStr = (String) redisTemplate.opsForHash().get(
                CacheConstants.IOT_DEVICE_LAST_DATA,
                iotId
        );
        if (StrUtil.isEmpty(jsonStr)){
            return new ArrayList<>();
        }
        // 反序列化为 Java 对象
        List<DeviceData> deviceDataList = JSONUtil.toList(jsonStr, DeviceData.class);
        if (CollUtil.isEmpty(deviceDataList)){
            return new ArrayList<>();
        }
        return deviceDataList.stream()
                .map(deviceData -> {
                    DeviceShadowDataVo vo = new DeviceShadowDataVo();
                    vo.setFunctionId(deviceData.getFunctionId());
                    vo.setEventTime(deviceData.getAlarmTime());
                    vo.setValue(deviceData.getDataValue());
                    return vo;
                })
                .collect(Collectors.toList());

    }

}
